package com.tensquare.search.controller;

import com.tensquare.search.pojo.Article;
import com.tensquare.search.service.ArticleService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 添加
     *
     * @param article
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result save(@RequestBody Article article) {
        if (article == null) {
            return new Result(false, StatusCode.PARAM_NULL, "参数不能为空！");
        }
        articleService.save(article);
        return new Result(true, StatusCode.OK, "添加成功！");
    }

    /**
     * 搜索
     *
     * @param key
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/{key}/{page}/{size}", method = RequestMethod.GET)
    public Result findByKey(@PathVariable String key, @PathVariable Integer page, @PathVariable Integer size) {
        Page<Article> articlePage = articleService.findByTitleLike(key, page, size);
        if (articlePage.getContent().size() == 0) {
            return new Result(false, StatusCode.RESULT_NULL, "没有查询到相关内容！");
        }
        return new Result(true, StatusCode.OK, "查询成功",
                new PageResult<Article>(articlePage.getTotalElements(),
                        articlePage.getContent()));
    }
}
